package com.zhousb.deviceManager.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhousb.deviceManager.exception.CustomerException;
import com.zhousb.deviceManager.mapper.*;
import com.zhousb.deviceManager.model.bo.AssetBo;
import com.zhousb.deviceManager.model.dto.AssetImportDto;
import com.zhousb.deviceManager.model.entity.*;
import com.zhousb.deviceManager.model.so.AssetSo;
import com.zhousb.deviceManager.model.vo.AssetVo;
import com.zhousb.deviceManager.security.JwtUser;
import com.zhousb.deviceManager.service.AssetLifecycleService;
import com.zhousb.deviceManager.service.AssetService;
import com.zhousb.deviceManager.utils.AuthUtils;
import com.zhousb.deviceManager.utils.IdGenerator;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author zhousb
 * @date 2024/10/29 14:55
 * @description
 */
@Service
public class AssetServiceImpl implements AssetService {

    @Resource
    private KiAssetMapper kiAssetMapper;
    @Resource
    private KiClientMapper kiClientMapper;
    @Resource
    private KiFloorMapper kiFloorMapper;
    @Resource
    private KiPositionMapper kiPositionMapper;
    @Resource
    private AuthUtils authUtils;
    @Resource
    private AssetLifecycleService assetLifecycleService;
    @Resource
    private KiAssetLifecycleMapper kiAssetLifecycleMapper;
    @Resource
    private KiAssetEpcRelationMapper kiAssetEpcRealtionMapper;
    @Resource
    SysUserClientMapper sysUserClientMapper;


    @Override
    public IPage<AssetVo> page(Page page, AssetSo so) {
        LambdaQueryWrapper<KiAsset> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(so.getKeyword()), KiAsset::getAssetCode, so.getKeyword());

        List<Long> clientIds = new ArrayList<>();
        if (StringUtils.isNotBlank(so.getClientId())) {
            clientIds.add(Long.valueOf(so.getClientId()));
        } else {
            if(!(authUtils.getUser().getRoles().contains("SUPER_ADMIN") ||authUtils.getUser().getRoles().contains("ADMIN"))){
                LambdaQueryWrapper<SysUserClient> sysUserClientQueryWrapper = new LambdaQueryWrapper<>();
                sysUserClientQueryWrapper.eq(SysUserClient::getUserId, authUtils.getUser().getUserId());
                List<SysUserClient> userClients = sysUserClientMapper.selectList(sysUserClientQueryWrapper);
                if (userClients.isEmpty()) {
                    return page;
                }
                clientIds = userClients.stream().map(SysUserClient::getClientId).toList();
            }

        }
return kiAssetMapper.page(page,so,clientIds);
//        queryWrapper.eq(StringUtils.isNotBlank(so.getFloorId()), KiAsset::getAssetFloor, so.getFloorId());
//        queryWrapper.eq(StringUtils.isNotBlank(so.getPositionId()), KiAsset::getAssetPosition, so.getPositionId());
//
//        List<KiClient> clients = kiClientMapper.selectList(null);
//        Map<Long, String> clientMap = clients.stream().collect(Collectors.toMap(KiClient::getId, KiClient::getClientName));
//        List<KiAssetEpcRelation> relations = kiAssetEpcRealtionMapper.selectList(null);
//        Map<String, String> assetEpcMap = relations.stream().collect(Collectors.toMap(KiAssetEpcRelation::getAssetCode, KiAssetEpcRelation::getEpc));
//        Page rawData = kiAssetMapper.selectPage(page, queryWrapper);
//        List<KiAsset> rawList = rawData.getRecords();
//        List<AssetVo> result = rawList.stream().map(s -> {
//            AssetVo vo = new AssetVo();
//            BeanUtils.copyProperties(s, vo);
//            vo.setClientName(clientMap.get(s.getClientId()));
//            vo.setAssetEpc(assetEpcMap.get(s.getAssetCode()));
//            return vo;
//        }).toList();
//        page.setRecords(result);
//        return page;
    }

    @Override
    public List<?> all(AssetSo so) {
        LambdaQueryWrapper<KiAsset> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KiAsset::getClientId, Long.valueOf(so.getClientId()))
                .isNotNull(KiAsset::getAssetEpc);
        return kiAssetMapper.selectList(queryWrapper);
    }

    @Override
    public boolean add(AssetBo bo) {
        JwtUser jwtUser = authUtils.getUser();
//        LambdaQueryWrapper<KiAsset> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(KiAsset::getAssetEpc, bo.getAssetEpc());
//        boolean exist = kiAssetMapper.exists(queryWrapper);
//        if (exist) {
//            throw new CustomerException("芯片码已存在");
//        }
        KiAsset kiAsset = new KiAsset();
        BeanUtils.copyProperties(bo, kiAsset);
        Long assetId = IdGenerator.nextId();
        kiAsset.setId(assetId);
        kiAsset.setClientId(Long.valueOf(bo.getClientId()));
        KiFloor kiFloor = null;
        if (StringUtils.isNotBlank(bo.getFloorName())) {
            LambdaQueryWrapper<KiFloor> floorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            floorLambdaQueryWrapper.eq(KiFloor::getClientId, bo.getClientId())
                    .eq(KiFloor::getFloor, bo.getFloorName());
            kiFloor = kiFloorMapper.selectOne(floorLambdaQueryWrapper);
            if (kiFloor == null) {
                kiFloor = new KiFloor();
                kiFloor.setClientId(Long.valueOf(bo.getClientId()));
                kiFloor.setFloor(bo.getFloorName());
                kiFloorMapper.insert(kiFloor);
            }
            kiAsset.setAssetFloor(kiFloor.getId());
        }
        if (StringUtils.isNotBlank(bo.getPositionName())) {
            LambdaQueryWrapper<KiPosition> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            positionLambdaQueryWrapper.eq(KiPosition::getFloorId, kiFloor.getId())
                    .eq(KiPosition::getPosition, bo.getPositionName());
            KiPosition kiPosition = kiPositionMapper.selectOne(positionLambdaQueryWrapper);
            if (kiPosition == null) {
                kiPosition = new KiPosition();
                kiPosition.setPosition(bo.getPositionName());
                kiPosition.setFloorId(kiFloor.getId());
                kiPositionMapper.insert(kiPosition);
            }
            kiAsset.setAssetPosition(kiPosition.getId());
        }

        LambdaQueryWrapper<KiAsset> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KiAsset::getClientId, Long.valueOf(bo.getClientId()))
                .eq(KiAsset::getAssetCode, bo.getAssetCode());
        boolean exist = kiAssetMapper.exists(queryWrapper);
        if (exist) {
            throw new CustomerException("资产编码重复");
        }
        kiAssetMapper.insert(kiAsset);

        KiAssetLifecycle lifecycle = new KiAssetLifecycle();
        lifecycle.setAssetId(assetId);
        lifecycle.setEventType("入库");
        lifecycle.setEventOperator(jwtUser.getUserId());
        lifecycle.setEventContent("手动入库");
        kiAssetLifecycleMapper.insert(lifecycle);
        return true;
    }


    @Override
    public boolean importExcel(String clientId, MultipartFile file) throws IOException {
        JwtUser jwtUser = authUtils.getUser();
        Map<String, ArrayList<String>> floorPositionMap = new HashMap<>();
        Map<String, Map<String, Long>> floorPositionIdMap = new HashMap<>();
        Map<String,Long> floorMap = new HashMap<>();

        List<AssetImportDto> rawList = EasyExcel.read(file.getInputStream())
                .head(AssetImportDto.class)
                .sheet()
                .doReadSync();


        for (AssetImportDto s : rawList) {
            LambdaQueryWrapper<KiFloor> floorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            floorLambdaQueryWrapper.eq(KiFloor::getClientId, Long.valueOf(clientId))
                    .eq(KiFloor::getFloor, s.getAssetFloor());
            KiFloor kiFloor = kiFloorMapper.selectOne(floorLambdaQueryWrapper);
            if (kiFloor == null) {
                kiFloor = new KiFloor();
                kiFloor.setFloor(s.getAssetFloor());
                kiFloor.setClientId(Long.valueOf(clientId));
                kiFloorMapper.insert(kiFloor);
            }

            LambdaQueryWrapper<KiPosition> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            positionLambdaQueryWrapper.eq(KiPosition::getFloorId, kiFloor.getId())
                    .eq(KiPosition::getPosition, s.getAssetPosition());
            KiPosition kiPosition = kiPositionMapper.selectOne(positionLambdaQueryWrapper);
            if (kiPosition == null) {
                kiPosition = new KiPosition();
                kiPosition.setFloorId(kiFloor.getId());
                kiPosition.setPosition(s.getAssetPosition());
                kiPositionMapper.insert(kiPosition);
            }

            List<String> positionList = floorPositionMap.getOrDefault(s.getAssetFloor(), new ArrayList<>());
            if (positionList.isEmpty()) {
                ArrayList<String> positions = new ArrayList<>();
                positions.add(s.getAssetPosition());
                floorPositionMap.put(s.getAssetFloor(), positions);
                Map<String, Long> positionMap = new HashMap<>();
                positionMap.put(kiPosition.getPosition(), kiPosition.getId());
                floorPositionIdMap.put(kiFloor.getFloor(), positionMap);

                floorMap.put(kiFloor.getFloor(), kiFloor.getId());
            } else {
                if (!positionList.contains(s.getAssetPosition())) {
                    positionList.add(s.getAssetPosition());
                    floorPositionIdMap.get(kiFloor.getFloor()).put(kiPosition.getPosition(), kiPosition.getId());
                }
            }

        }


        List<KiAsset> assetList = new ArrayList<>();
        List<KiAssetLifecycle> lifecycleList = new ArrayList<>();
        for (AssetImportDto s : rawList) {
            KiAsset kiAsset = new KiAsset();
            Long assetId = IdGenerator.nextId();
            kiAsset.setId(assetId);
            kiAsset.setAssetCode(s.getAssetCode());
            kiAsset.setAssetEpc(s.getAssetEpc());
            kiAsset.setAssetName(s.getAssetName());
            kiAsset.setClientId(Long.parseLong(clientId));
            kiAsset.setAssetFloor(floorMap.get(s.getAssetFloor()));
            kiAsset.setAssetPosition(floorPositionIdMap.get(s.getAssetFloor()).get(s.getAssetPosition()));
            kiAsset.setAddress(s.getAddress());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("label", "颜色");
            jsonObject.set("value", s.getExtend1());
            jsonObject.set("index", 1);
            jsonArray.add(jsonObject);
            kiAsset.setExtend(JSONUtil.toJsonStr(jsonArray));

            assetList.add(kiAsset);

            KiAssetLifecycle lifecycle = new KiAssetLifecycle();
            lifecycle.setAssetId(assetId);
            lifecycle.setEventType("初始化");
            lifecycle.setEventContent("初始化导入");
            lifecycle.setEventOperator(jwtUser.getUserId());
            lifecycleList.add(lifecycle);
        }

        kiAssetMapper.batchInsert(assetList);

        assetLifecycleService.batchInsert(lifecycleList, 100);
        return true;
    }
}
